package com.jsch.test;

import com.jcraft.jsch.*;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

public class SshUtil {
    private ChannelSftp channelSftp;
    private ChannelExec channelExec;
    private Session session = null;
    private int timeout = 60000;

    public SshUtil(SshConfiguration conf) throws JSchException {
        System.out.println("try connect to  " + conf.getHost() + ",username: " + conf.getUserName() + ",password: " + conf.getPassword() + ",port: " + conf.getPort());
        JSch jSch = new JSch(); //创建JSch对象
        session = jSch.getSession(conf.getUserName(), conf.getHost(), conf.getPort());//根据用户名，主机ip和端口获取一个Session对象
        session.setPassword(conf.getPassword()); //设置密码
        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);//为Session对象设置properties
        session.setTimeout(timeout);//设置超时
        session.connect();//通过Session建立连接
    }

    public void download(String src, String dst) throws JSchException, SftpException {
        //src linux服务器文件地址，dst 本地存放地址
        channelSftp = (ChannelSftp) session.openChannel("sftp");
        channelSftp.connect();
        channelSftp.get(src, dst);
        channelSftp.quit();
    }

    public void upLoad(String src, String dst) throws JSchException, SftpException {
        //src 本机文件地址。 dst 远程文件地址
        channelSftp = (ChannelSftp) session.openChannel("sftp");
        channelSftp.connect();
        channelSftp.put(src, dst);
        channelSftp.quit();
    }

    public void close() {
        session.disconnect();
    }

    public List<String> remoteExecute(String command) throws JSchException {
        List<String> resultLines = new ArrayList<>();
        ChannelExec channel = null;
        try {
            channel = (ChannelExec) session.openChannel("exec");
            channel.setCommand(command);
            InputStream input = channel.getInputStream();
            channel.connect(timeout);
            try {
                BufferedReader inputReader = new BufferedReader(new InputStreamReader(input));
                String inputLine = null;
                while ((inputLine = inputReader.readLine()) != null) {
                    resultLines.add(inputLine);
                }
            } finally {
                if (input != null) {
                    try {
                        input.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (channel != null) {
                try {
                    channel.disconnect();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return resultLines;
    }

    public static void main(String[] args) {
        SshConfiguration configuration = new SshConfiguration();
        configuration.setHost("localhost");//185.23.200.178
        configuration.setUserName("chaoxing.hou");//root
        configuration.setPassword("hCx@123456");//Hcx123456
        configuration.setPort(5200);
        try {
            SshUtil sshUtil = new SshUtil(configuration);
            for (int j = 0; j < 10; j++) {
                System.out.println("开始请求：" + System.currentTimeMillis());
                List<String> rs = sshUtil.remoteExecute("ls -l");
                for (int i = 0; i < rs.size(); i++) {
                    System.out.println(rs.get(i));
                }
                System.out.println("完成请求：" + System.currentTimeMillis());
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            sshUtil.close();
        } catch (JSchException e) {
            e.printStackTrace();
        }

    }

    public static void main1(String[] args) {
        SshConfiguration configuration = new SshConfiguration();
        configuration.setHost("localhost");
        configuration.setUserName("chaoxing.hou");
        configuration.setPassword("hCx@123456");
        configuration.setPort(5200);
        try {
            SshUtil sshUtil = new SshUtil(configuration);
            sshUtil.download("/Users/chaoxing.hou/Downloads/wsl/test_img.JPG", "/Users/chaoxing.hou/Downloads/");
            sshUtil.close();
            System.out.println("文件下载完成");


//            SshUtil sshUtil = new SshUtil(configuration);
//            sshUtil.upLoad("/Users/chaoxing.hou/Downloads/sytem_config.txt", "/root/myfile/upload/");
//            sshUtil.close();
//            System.out.println("文件上传完成");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}